from PyCmpltrtok.common import sep
from neo4j import GraphDatabase
from python_nlp.kg.neo4j.config import NEO4J_CONFIG_AGR
from x00100_confirm_location import confirm_location
from x00150_nav import choose, level_up_or_down


def query_climate(driver, xlocation):
    sep(xlocation)
    with driver.session() as ss:
        cypher = 'match (n:Node{name:%r})-[r:Predicate{name:%r}]-(m:Node) return m.name' % (xlocation, '气候', )
        record = ss.run(cypher)
        if record:
            for row in record:
                xclimate = row[0]
                return xclimate
    return None


def determine_climate(driver, xlocation):

    def process_nodes(nodes):
        if not nodes:
            return None
        new_nodes = []
        for node in nodes:
            c = query_climate(driver, node)
            if c:
                return c
            ups = level_up_or_down(driver, node, 'up')
            new_nodes.extend(ups)
        return process_nodes(new_nodes)

    return process_nodes([xlocation])


def determine_plant(driver, xclimate, xlimit=0):

    assert isinstance(xlimit, int) and xlimit >= 0

    if not xlimit:
        limit_str = ''
    else:
        limit_str = f' LIMIT {xlimit} '

    xplants = []
    with driver.session() as ss:
        cypher = 'match (n:Node{name:%r})-[r:Predicate{name:%r}]-(m:Node) return m.name %s' % (xclimate, '适合种植', limit_str)
        record = ss.run(cypher)
        if record:
            for i, row in enumerate(record):
                xplant = row[0]
                xplants.append(xplant)
    return xplants

if '__main__' == __name__:

    def _main():
        # 驱动
        driver = GraphDatabase.driver(**NEO4J_CONFIG_AGR)

        while True:
            sep()
            print('请输入查询的地区：')
            xname = input().strip()
            xcandidates = confirm_location(driver, xname)

            if not xcandidates:
                continue

            xlen = len(xcandidates)
            if 1 == xlen:
                xtarget = xcandidates[0]
            else:
                xtarget = choose(xcandidates)

            sep(xtarget)
            xclimate = determine_climate(driver, xtarget)
            print(xtarget, '的气候是', xclimate)
            if isinstance(xclimate, str):
                xplants = determine_plant(driver, xclimate, xlimit=10)
                print('适于种植', xplants)

    _main()
